<template>
  <div class="knowledge-manage">
    <!-- 页面头部 -->
    <el-row align="middle" justify="space-between" class="knowledge-header">
      <el-col>
        <el-page-header content="知识库管理" />
      </el-col>
      <el-col>
        <el-button type="primary" @click="openEditDialog()">添加知识</el-button>
        <el-button type="info" @click="openCategoryDialog()" style="margin-left: 8px;">分类管理</el-button>
      </el-col>
    </el-row>

    <!-- 统计卡片区 -->
    <el-row :gutter="20" class="knowledge-stats" style="margin: 24px 0;">
      <el-col :span="6">
        <el-card>
          <div class="stat-title">总知识条数</div>
          <div class="stat-value">{{ stats.totalKnowledge }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card>
          <div class="stat-title">知识分类</div>
          <div class="stat-value">{{ stats.totalCategories }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card>
          <div class="stat-title">总浏览量</div>
          <div class="stat-value">{{ stats.totalViews }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card>
          <div class="stat-title">有用率</div>
          <div class="stat-value">{{ stats.helpfulRate }}%</div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 筛选器/搜索栏 -->
    <el-card class="knowledge-filter-bar" style="margin-bottom: 20px;">
      <el-row :gutter="16" align="middle">
        <el-col :span="6">
          <el-select v-model="filter.category" placeholder="全部分类" clearable style="width: 100%;">
            <el-option v-for="cat in flatCategories" :key="cat.id" :label="cat.name" :value="cat.id" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-select v-model="filter.sort" placeholder="排序方式" style="width: 100%;">
            <el-option label="创建时间" value="created" />
            <el-option label="更新时间" value="updated" />
            <el-option label="浏览量" value="views" />
            <el-option label="有用度" value="helpful" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-select v-model="filter.status" placeholder="发布状态" style="width: 100%;">
            <el-option label="全部" value="all" />
            <el-option label="已发布" value="published" />
            <el-option label="草稿" value="draft" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-input v-model="filter.keyword" placeholder="搜索知识内容..." clearable @keyup.enter="doSearch" />
        </el-col>
      </el-row>
    </el-card>

    <!-- 知识卡片区（后续可拆分为子组件） -->
    <el-row :gutter="20" class="knowledge-grid">
      <el-col :span="8" v-for="item in filteredKnowledge" :key="item.id">
        <el-card shadow="hover" class="knowledge-card">
          <div class="knowledge-card-header">
            <div class="knowledge-card-title">{{ item.title }}</div>
            <div class="knowledge-card-category">{{ getCategoryName(item.categoryId) }}</div>
          </div>
          <div class="knowledge-card-body">
            <div class="knowledge-card-content" v-html="item.content"></div>
            <div class="knowledge-card-tags">
              <el-tag v-for="tag in item.tags" :key="tag" size="small">{{ tag }}</el-tag>
            </div>
            <div class="knowledge-card-meta">
              <span>权重: {{ item.weight }}</span>
              <span>浏览: {{ item.views }}</span>
            </div>
            <div class="knowledge-card-actions">
              <el-button type="primary" size="small" @click="viewDetail(item)">查看</el-button>
              <el-button type="warning" size="small" @click="openEditDialog(item)">编辑</el-button>
              <el-button type="danger" size="small" @click="deleteKnowledge(item)">删除</el-button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 新建/编辑知识弹窗 -->
    <KnowledgeEditDialog
      v-if="editDialogVisible"
      :visible="editDialogVisible"
      :modelValue="editDialogData"
      :categoryOptions="categories"
      @update:visible="editDialogVisible = $event"
      @save="handleSaveKnowledge"
    />

    <!-- 分类管理弹窗 -->
    <CategoryManageDialog
      v-if="categoryDialogVisible"
      :visible="categoryDialogVisible"
      :categories="categories"
      @update:visible="categoryDialogVisible = $event"
      @update:categories="handleUpdateCategories"
    />

    <!-- 知识详情弹窗（后续实现） -->
    <el-dialog v-model="detailDialogVisible" title="知识详情" width="800px">
      <div v-if="currentDetail">
        <h3>{{ currentDetail.title }}</h3>
        <div v-html="currentDetail.content"></div>
      </div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, reactive } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import KnowledgeEditDialog from './components/KnowledgeEditDialog.vue'
import CategoryManageDialog from './components/CategoryManageDialog.vue'
import { knowledgeList, categories } from '@/mock/knowledge'

// 统计信息
const stats = computed(() => ({
  totalKnowledge: knowledgeList.value.length,
  totalCategories: categories.value.length,
  totalViews: knowledgeList.value.reduce((sum, k) => sum + k.views, 0),
  helpfulRate: knowledgeList.value.length
    ? Math.round(
        (knowledgeList.value.reduce((sum, k) => sum + k.helpful, 0) /
          (knowledgeList.value.length * 100)) * 100
      )
    : 0,
}))

// 扁平化分类（用于下拉选择）
const flatCategories = computed(() => categories.value)

// 筛选条件
const filter = reactive({
  category: '',
  sort: 'created',
  status: 'all',
  keyword: '',
})

// 知识库筛选
const filteredKnowledge = computed(() => {
  let list = knowledgeList.value.slice()
  if (filter.category) {
    list = list.filter(k => String(k.categoryId) === String(filter.category))
  }
  if (filter.status !== 'all') {
    list = list.filter(k => k.status === filter.status)
  }
  if (filter.keyword) {
    list = list.filter(k =>
      k.title.includes(filter.keyword) ||
      k.content.includes(filter.keyword) ||
      (k.tags && k.tags.some(t => t.includes(filter.keyword)))
    )
  }
  // 排序
  if (filter.sort === 'created') {
    list.sort((a, b) => b.created.localeCompare(a.created))
  } else if (filter.sort === 'updated') {
    list.sort((a, b) => b.updated.localeCompare(a.updated))
  } else if (filter.sort === 'views') {
    list.sort((a, b) => b.views - a.views)
  } else if (filter.sort === 'helpful') {
    list.sort((a, b) => b.helpful - a.helpful)
  }
  return list
})

// 弹窗控制
const editDialogVisible = ref(false)
const editDialogData = ref<any>(null)
// 分类管理弹窗控制
const categoryDialogVisible = ref(false)
function openCategoryDialog() {
  categoryDialogVisible.value = true
}
function handleUpdateCategories(newList: any[]) {
  categories.value = newList
}
const detailDialogVisible = ref(false)
const currentDetail = ref<any>(null)

function openEditDialog(item?: any) {
  if (item) {
    editDialogData.value = { ...item }
  } else {
    // 新增时清空表单
    editDialogData.value = null
  }
  editDialogVisible.value = true
}
function viewDetail(item: any) {
  currentDetail.value = item
  detailDialogVisible.value = true
}
function deleteKnowledge(item: any) {
  ElMessageBox.confirm('确定要删除该知识吗？', '提示', { type: 'warning' })
    .then(() => {
      knowledgeList.value = knowledgeList.value.filter(k => k.id !== item.id)
    })
    .catch(() => {})
}
function getCategoryName(id: number) {
  const cat = categories.value.find(c => c.id === id)
  return cat ? cat.name : '-'
}
function doSearch() {
  // 触发筛选即可，已响应式
}
function handleSaveKnowledge(data: any) {
  if (editDialogData.value && editDialogData.value.id) {
    // 编辑
    const idx = knowledgeList.value.findIndex(k => k.id === editDialogData.value.id)
    if (idx > -1) knowledgeList.value[idx] = { ...editDialogData.value, ...data, updated: new Date().toISOString().slice(0,10) }
    ElMessage.success('知识编辑成功')
  } else {
    // 新增
    const newId = knowledgeList.value.length ? Math.max(...knowledgeList.value.map(k => k.id)) + 1 : 1
    knowledgeList.value.unshift({
      ...data,
      id: newId,
      views: 0,
      helpful: 0,
      created: new Date().toISOString().slice(0,10),
      updated: new Date().toISOString().slice(0,10)
    })
    ElMessage.success('知识添加成功')
  }
  editDialogVisible.value = false
}
</script>

<style scoped>
.knowledge-header {
  margin-bottom: 20px;
}
.knowledge-stats .stat-title {
  font-size: 14px;
  color: #888;
}
.knowledge-stats .stat-value {
  font-size: 24px;
  font-weight: bold;
  margin-top: 8px;
}
.knowledge-card-title {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 8px;
}
.knowledge-card-category {
  font-size: 12px;
  color: #999;
  margin-bottom: 8px;
}
.knowledge-card-content {
  min-height: 48px;
  color: #333;
  margin-bottom: 12px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}
.knowledge-card-tags {
  margin-bottom: 8px;
}
.knowledge-card-meta {
  display: flex;
  justify-content: space-between;
  color: #aaa;
  font-size: 12px;
  margin-bottom: 8px;
}
.knowledge-card-actions {
  display: flex;
  gap: 8px;
}
</style>
 